﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Input;

using TournamentDatabase.DialogBoxes.Edit;
using TournamentDatabase.Objects;
using TournamentDatabase.Database;
using TournamentDatabase.Singletons;

namespace TournamentDatabase.DialogBoxes.Select
{
	/// <summary>
	/// Interaction logic for TournamentSelectDialogBox.xaml
	/// </summary>
	public partial class TournamentSelectDialogBox : Window
	{
		Tournament m_selectedTournament;
		List<Tournament> m_tournamentList;
		string m_currentSearch;

		public List<Tournament> TournamentList
		{
			get { return m_tournamentList; }
			set { m_tournamentList = value; }
		}

		public Tournament SelectedTournament
		{
			get { return m_selectedTournament; }
			set { m_selectedTournament = value; }
		}

		public TournamentSelectDialogBox()
		{
			InitializeComponent();

			Search();

			this.DataContext = this;
		}

		private void createTournamentButton_Click(object sender, RoutedEventArgs e)
		{
			TournamentEditDialogBox medb = new TournamentEditDialogBox();

			medb.ShowDialog();

			if (medb.DialogResult.HasValue && medb.DialogResult.Value)
			{
				Search();
				e.Handled = true;
			}
		}

		private void selectButton_Click(object sender, RoutedEventArgs e)
		{
			if (m_selectedTournament != null)
			{
				DialogResult = true;
			}
		}

		private void OnSearch(string searchText)
		{
			m_currentSearch = searchText;
			Search();
		}

		private void Search()
		{
			if (m_currentSearch == null || m_currentSearch.Length == 0)
			{
				m_tournamentList = DatabaseSingleton.GetDatabaseAccessor().QueryTournament("", OrderBy.None, "");
			}
			else
			{
				string where = "title LIKE '%" + m_currentSearch + "%'";
				m_tournamentList = DatabaseSingleton.GetDatabaseAccessor().QueryTournament(where, OrderBy.None, "");
			}
		}
	}
}
